package com.test.connection;

import org.json.JSONArray;
import org.json.JSONObject;

import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

import static com.test.connection.ConnectionTest.*;

/**
 * Created by yang on 17/3/13.
 */
public class StuSubmit {

    public static String homeworkId = null;
    public static String hwQuestion = null;
    public static List<String> questionId = new ArrayList<>();
    public static List<String> rightAnswer = new ArrayList<>();


    public static void openHomework() throws Exception {

        StuGetToken.getToken();

        System.out.println("请输入homeworkID： ");
        // 输入homeworkId
        Scanner input = new Scanner(System.in);
        homeworkId = input.nextLine();

        // question-list请求url
        String path = "http://stuapi.knowbox.cn/homework/once/question-list";
        String url = null;

        // 构造question-list请求参数
        for (int i = 0; i < StuGetToken.tokens.size(); i++) {
            url = path+"?"+"token="+StuGetToken.tokens.get(i)+"&homeworkID="+homeworkId;
        }
        hwQuestion = ConnectionTest.sendGet(url);
//        System.out.println(hwQuestion);
    }

    public static void getAnswer() throws Exception {

        StuSubmit.openHomework();
        System.out.println(StuSubmit.hwQuestion);
        if (StuSubmit.hwQuestion != null && !StuSubmit.hwQuestion.isEmpty()){
            JSONObject jsonObject = new JSONObject(StuSubmit.hwQuestion);
            JSONArray jsonArray = jsonObject.optJSONArray("questionList");
            for (int i = 0; i < jsonArray.length(); i++) {
                JSONObject quesJson = jsonArray.getJSONObject(i);
                StuSubmit.questionId.add(quesJson.optString("questionID"));
                StuSubmit.rightAnswer.add(quesJson.optString("rightAnswer"));
            }
        }
    }

    public static void submit() throws Exception {
        StuSubmit.getAnswer();

        String path = "http://stuapi.knowbox.cn/homework/once/commit";
        JSONArray requesList = new JSONArray();
        // 获取答案list
        for (int i = 0; i < StuSubmit.questionId.size(); i++) {
            JSONObject requesOne = new JSONObject();
            requesOne.put("questionID", StuSubmit.questionId.get(i));
            requesOne.put("answer", StuSubmit.rightAnswer.get(i));
            requesOne.put("spendTime", "100000");
            requesList.put(requesOne);
        }

//        System.out.println(requesList);
        for (int i = 0; i < StuGetToken.tokens.size(); i++) {

            JSONObject request = new JSONObject();
            request.put("list", requesList);
            request.put("token", StuGetToken.tokens.get(i));
            request.put("homeworkID", StuSubmit.homeworkId);

            String params = request.toString();
            System.out.println("params=" + request);


            System.out.println(ConnectionTest.sendPost(path,params.toString()));

        }
    }
}
